package org.unique.support.template;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jetbrick.io.resource.ResourceNotFoundException;
import jetbrick.template.JetEngine;
import jetbrick.template.JetTemplate;
import jetbrick.template.web.JetWebContext;
import jetbrick.template.web.JetWebEngine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unique.Const;
import org.unique.web.core.WebContext;
import org.unique.web.render.Render;

/**
 * jetbrick render
 * 
 * @author biezhi
 * @version 1.0
 */
public class JetRender implements Render {

	private static final Logger LOGGER = LoggerFactory.getLogger(JetRender.class);
	private static final String contentType = "text/html;charset=" + Const.ENCODING;
	private static final String rootPath = Const.getConfig("unique.view.prefix");
	private JetEngine engine;
	
	public JetRender() {
		engine = JetWebEngine.create(WebContext.getServletContext());
	}
	
	
	public void render(HttpServletRequest request, HttpServletResponse response, String viewPath) {
		
		String view = rootPath + viewPath + suffix;
		if (viewPath.endsWith(suffix)) {
			view = viewPath;
		}
		
		view = view.replaceAll("(//)+", "/");
		
		LOGGER.debug("view：[{}]", view);
		
		response.setContentType(contentType);
		response.setCharacterEncoding(Const.ENCODING);
		
		 try {
            JetTemplate template = engine.getTemplate(view);
            JetWebContext context = new JetWebContext(request, response);
            template.render(context, response.getOutputStream());
        } catch (ResourceNotFoundException e) {
            try {
				response.sendError(HttpServletResponse.SC_NOT_FOUND, "模板文件没有被找到: " + view);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
        } catch (IOException e) {
			e.printStackTrace();
		}
	}

}
